#include "qrsagsdbmanagermainwindow.h"
#include "ui_qrsagsdbmanagermainwindow.h"
#include "qgsapplication.h"
#include "qgsdatasourceuri.h"
#include "qgsmessagebar.h"
#include "qgssettings.h"
#include "qgsproject.h"
#include "qgslayertree.h"
#include "qgscoordinatereferencesystem.h"
#include "qgsdataprovider.h"
#include "qgsvectorlayerexporter.h"
#include "qgspostgresproviderconnection.h"

#include <QMessageBox>

QRSAGSDBManagerMainWindow::QRSAGSDBManagerMainWindow(QWidget *parent, QString connName) :
    QMainWindow(parent),
    mOriginalConnName(connName),
    ui(new Ui::QRSAGSDBManagerMainWindow)
{
    ui->setupUi(this);
    this->setAttribute(Qt::WA_DeleteOnClose);

    //初始化PostGIS数据库连接部分代码
    initPostGISConnection();
}

QRSAGSDBManagerMainWindow::~QRSAGSDBManagerMainWindow()
{
    if(mPostgresConn){
        mPostgresConn->unref();
    }
    delete ui;
}

void QRSAGSDBManagerMainWindow::initPostGISConnection()
{
    connect( ui->mTestConnectButton, &QPushButton::clicked, this, &QRSAGSDBManagerMainWindow::testConnection);
    connect( ui->mConnectionButton, &QPushButton::clicked, this, &QRSAGSDBManagerMainWindow::connectPostgreDatabase );
    connect( ui->cb_geometryColumnsOnly, &QCheckBox::clicked, this, &QRSAGSDBManagerMainWindow::cb_geometryColumnsOnly_clicked );
    connect( ui->mClearButton, &QPushButton::clicked, this, [=](bool){
        ui->txtName->clear();
        ui->txtHost->clear();
        ui->txtPort->clear();
        ui->txtDatabase->clear();
        ui->mAuthSettings->setUsername("");
        ui->mAuthSettings->setPassword("");
    });
    connect( ui->mQuitButton,  &QPushButton::clicked, this, [=](bool){
        if(mPostgresConn){
            mPostgresConn->unref();
        }
        this->close();
    });

    connect( ui->txtName, &QLineEdit::textChanged, this, &QRSAGSDBManagerMainWindow::updateOkButtonState );
    connect( ui->txtHost, &QLineEdit::textChanged, this, &QRSAGSDBManagerMainWindow::updateOkButtonState );
    connect( ui->txtPort, &QLineEdit::textChanged, this, &QRSAGSDBManagerMainWindow::updateOkButtonState );
    connect( ui->txtDatabase, &QLineEdit::textChanged, this, &QRSAGSDBManagerMainWindow::updateOkButtonState );

    ui->cbxSSLmode->addItem( tr( "disable" ), QgsDataSourceUri::SslDisable );
    ui->cbxSSLmode->addItem( tr( "allow" ), QgsDataSourceUri::SslAllow );
    ui->cbxSSLmode->addItem( tr( "prefer" ), QgsDataSourceUri::SslPrefer );
    ui->cbxSSLmode->addItem( tr( "require" ), QgsDataSourceUri::SslRequire );
    ui->cbxSSLmode->addItem( tr( "verify-ca" ), QgsDataSourceUri::SslVerifyCa );
    ui->cbxSSLmode->addItem( tr( "verify-full" ), QgsDataSourceUri::SslVerifyFull );

    ui->mAuthSettings->setDataprovider(QStringLiteral("postgres"));
    ui->mAuthSettings->showStoreCheckboxes( true );

    if (!mOriginalConnName.isEmpty())
    {
        // populate the dialog with the information stored for the connection
        // populate the fields with the stored setting parameters
        QgsSettings settings;

        QString key = "/PostgreSQL/connections/" + mOriginalConnName;
        ui->txtHost->setText( settings.value( key + "/host" ).toString() );
        QString port = settings.value( key + "/port" ).toString();
        if ( port.length() == 0 )
        {
            port = QStringLiteral( "5432" );
        }
        ui->txtPort->setText( port );
        ui->txtDatabase->setText( settings.value( key + "/database" ).toString() );
        ui->cb_publicSchemaOnly->setChecked( settings.value( key + "/publicOnly", false ).toBool() );
        ui->cb_geometryColumnsOnly->setChecked( settings.value( key + "/geometryColumnsOnly", true ).toBool() );
        ui->cb_dontResolveType->setChecked( settings.value( key + "/dontResolveType", false ).toBool() );
        ui->cb_allowGeometrylessTables->setChecked( settings.value( key + "/allowGeometrylessTables", false ).toBool() );
        // Ensure that cb_publicSchemaOnly is set correctly
        cb_geometryColumnsOnly_clicked();

        ui->cb_useEstimatedMetadata->setChecked( settings.value( key + "/estimatedMetadata", false ).toBool() );
        ui->cb_projectsInDatabase->setChecked( settings.value( key + "/projectsInDatabase", false ).toBool() );

        ui->cbxSSLmode->setCurrentIndex( ui->cbxSSLmode->findData( settings.enumValue( key + "/sslmode", QgsDataSourceUri::SslPrefer ) ) );

        if ( settings.value( key + "/saveUsername" ).toString() == QLatin1String( "true" ) )
        {
            ui->mAuthSettings->setUsername( settings.value( key + "/username" ).toString() );
            ui->mAuthSettings->setStoreUsernameChecked( true );
        }

        if ( settings.value( key + "/savePassword" ).toString() == QLatin1String( "true" ) )
        {
            ui->mAuthSettings->setPassword( settings.value( key + "/password" ).toString() );
            ui->mAuthSettings->setStorePasswordChecked( true );
        }

        // Old save setting
        if ( settings.contains( key + "/save" ) )
        {
            ui->mAuthSettings->setUsername( settings.value( key + "/username" ).toString() );
            ui->mAuthSettings->setStoreUsernameChecked( !ui->mAuthSettings->username().isEmpty() );

            if ( settings.value( key + "/save" ).toString() == QLatin1String( "true" ) )
                ui->mAuthSettings->setPassword( settings.value( key + "/password" ).toString() );

            ui->mAuthSettings->setStorePasswordChecked( true );
        }

        QString authcfg = settings.value( key + "/authcfg" ).toString();
        ui->mAuthSettings->setConfigId( authcfg );

        ui->txtName->setText( mOriginalConnName );
    }
    ui->txtName->setValidator( new QRegExpValidator( QRegExp( "[^\\/]*" ), ui->txtName));
}

void QRSAGSDBManagerMainWindow::initImportDataToPostGIS()
{
    //初始化输入信息
    ui->cboInputLayer->clear();
    QList<QgsLayerTreeLayer *> treeLayers = QgsProject::instance()->layerTreeRoot()->findLayers();
    if(treeLayers.size() <= 0){
        QMessageBox::information(this, tr("information"), tr("There is no maplayer in canvas..."));
    }

    for(QgsLayerTreeLayer *treeLayer : treeLayers){
        QgsMapLayer *layer = treeLayer->layer();
        if(layer && layer->type() == QgsMapLayerType::VectorLayer){
            ui->cboInputLayer->addItem(layer->name(), layer->id());
        }
    }

    //初始化输出数据表
    ui->cboSchema->addItems(mSchemaSet.toList());
    if(mSchemaSet.contains("public")){
        ui->cboSchema->setCurrentText("public");
    }
    if(mSchema2Tables.size() > 0){
        QStringList currentTables = mSchema2Tables.value(ui->cboSchema->currentText());
        if(!currentTables.contains(ui->cboInputLayer->currentText())){
            currentTables.append(ui->cboInputLayer->currentText());
        }
        ui->cboTable->addItems(currentTables);
        ui->cboTable->setCurrentText(ui->cboInputLayer->currentText());
    }else {
        ui->cboTable->addItem(ui->cboInputLayer->currentText());
    }

    //初始化选项内容
    QString layerId = ui->cboInputLayer->currentData().toString();
    if(layerId.isEmpty()){
        return;
    }
    QgsMapLayer *currentMapLayer = QgsProject::instance()->mapLayer(layerId);
    QgsDataSourceUri srcUri(currentMapLayer->source());
    QString srcPK = srcUri.keyColumn();
    QString srcGeom = srcUri.geometryColumn();
    ui->editPrimaryKey->setText(!srcPK.isEmpty()?srcPK:mDefaultPK);
    ui->editGeomColumn->setText(!srcGeom.isEmpty()?srcGeom:mDefaultGeom);
    QgsCoordinateReferenceSystem currentCRS = currentMapLayer->crs();
    if(!currentCRS.isValid()){
        currentCRS = QgsCoordinateReferenceSystem("EPSG:4326");
    }
    ui->widgetSourceSrid->setCrs(currentCRS);
    ui->widgetTargetSrid->setCrs(currentCRS);

    //初始化连接信息
    connect(ui->cboSchema, &QComboBox::currentTextChanged, this, [=](QString){
        ui->cboTable->clear();
        ui->cboTable->addItems(mSchema2Tables.value(ui->cboSchema->currentText()));
    });
    connect(ui->chkPrimaryKey, &QCheckBox::stateChanged, this, [=](int){ui->editPrimaryKey->setEnabled(ui->chkPrimaryKey->isChecked());});
    connect(ui->chkGeomColumn, &QCheckBox::clicked, this, [=](int){ui->editGeomColumn->setEnabled(ui->chkGeomColumn->isChecked());});
    connect(ui->chkSourceSrid, &QCheckBox::clicked, this, [=](int){ui->widgetSourceSrid->setEnabled(ui->chkSourceSrid->isChecked());});
    connect(ui->chkTargetSrid, &QCheckBox::clicked, this, [=](int){ui->widgetTargetSrid->setEnabled(ui->chkTargetSrid->isChecked());});
    connect(ui->chkEncoding, &QCheckBox::clicked, this, [=](int){ui->cboEncoding->setEnabled(ui->chkEncoding->isChecked());});
    connect(ui->chkCom, &QCheckBox::clicked, this, [=](int){ui->editCom->setEnabled(ui->chkCom->isChecked());});

    connect(ui->mImportDataToDBButton, SIGNAL(clicked(bool)), this, SLOT(importSelectedLayerToPostgreSQL(bool)));
}

void QRSAGSDBManagerMainWindow::initQueryDataFromPostGIS()
{
    //初始化查询的schema和table
    ui->cboSchemaQuery->addItems(mSchemaSet.toList());
    //如果架构中不包括public，那么这里认为数据表中没有满足要求的内容
    if(mSchemaSet.contains("public")){
        //给架构添加条目
        ui->cboSchemaQuery->setCurrentText("public");
        //这里指定只能从public中获取数据表
        if(mSchema2Tables.size() > 0){
            QStringList currentTables = mSchema2Tables.value(ui->cboSchemaQuery->currentText());
            ui->cboTableQuery->addItems(currentTables);
        }else {
            QMessageBox::information(this, tr("Warm Tips"), tr("There is not proper tables...."));
        }
    }else{
        QMessageBox::information(this, tr("Warm Tips"), tr("There is not schema named public...."));
    }

    QString currentTableName = ui->cboTableQuery->currentText();
    updateFieldListByTable(currentTableName);

    //根据数据查询中选择的表格名称，获取能够提供用来进行查询的字段对象
    connect(ui->cboTableQuery, SIGNAL(currentIndexChanged(QString)), this, SLOT(updateFieldListByTable(QString)));
    connect(ui->mExpressionQueryButton, SIGNAL(clicked(bool)), this, SLOT(expressionQuery(bool)));
    connect(ui->mExpressionClearButton, SIGNAL(clicked(bool)), this, SLOT(expressionClear(bool)));
    connect(ui->mQueryExpressionLineEdit, &QLineEdit::textChanged, this, [=](QString str){
        ui->mExpressionQueryButton->setEnabled(!str.trimmed().isEmpty());
        ui->mExpressionClearButton->setEnabled(!str.trimmed().isEmpty());
    });
}

void QRSAGSDBManagerMainWindow::updateFieldListByTable(QString tableName)
{
    QString currentSchema = ui->cboSchemaQuery->currentText();
    QVector<QgsPostgresLayerProperty> layers;
    bool getSupportedLayersResult = mPostgresConn->supportedLayers(layers, ui->cb_dontResolveType->isChecked(), ui->cb_publicSchemaOnly->isChecked(), ui->cb_allowGeometrylessTables->isChecked(), currentSchema);
    if(getSupportedLayersResult){
        for(QgsPostgresLayerProperty layerProperty: layers){
            if(tableName != layerProperty.tableName){
                continue;
            }

            //获取需要查询的图层后，获取图层的字段信息
            QgsDataSourceUri dataSourceUri = mPostgresConn->connUri(ui->txtName->text());
            QgsPostgresProviderConnection postgresProviderConn( dataSourceUri.uri(), QVariantMap());
            QgsFields fields = postgresProviderConn.fields(currentSchema,tableName);
            ui->mFieldComboBox->clear();
            ui->mFieldComboBox->addItems(fields.names());
        }
    }
}

void QRSAGSDBManagerMainWindow::testConnection()
{
    QgsTemporaryCursorOverride cursorOverride( Qt::WaitCursor );

    QgsDataSourceUri uri;
    uri.setConnection( ui->txtHost->text(), ui->txtPort->text(), ui->txtDatabase->text(),
                       ui->mAuthSettings->username(), ui->mAuthSettings->password(),
                       ( QgsDataSourceUri::SslMode ) ui->cbxSSLmode->currentData().toInt(),
                       ui->mAuthSettings->configId() );

    QgsPostgresConn *conn = QgsPostgresConn::connectDb(uri.connectionInfo(false),true);

    if ( conn )
    {
        if ( conn->pgVersion() < 90500 )
        {
            ui->cb_projectsInDatabase->setEnabled( false );
            ui->cb_projectsInDatabase->setChecked( false );
            ui->cb_projectsInDatabase->setToolTip( tr( "Saving projects in databases not available for PostgreSQL databases earlier than 9.5" ) );
        }
        else
        {
            ui->cb_projectsInDatabase->setEnabled( true );
            ui->cb_projectsInDatabase->setToolTip( QString() );
        }

        // Database successfully opened; we can now issue SQL commands.
        ui->statusBar->showMessage( tr( "Connection to %1 was successful." ).arg( ui->txtName->text() ));

        // free pg connection resources
        conn->unref();
    }
    else
    {
        ui->statusBar->showMessage( tr( "Connection failed - consult message log for details." ));
    }
}

void QRSAGSDBManagerMainWindow::connectPostgreDatabase()
{
    //断开之前的连接
    if(mPostgresConn){
        mPostgresConn->unref();
    }

    if(mColumnTypeThread){
        mColumnTypeThread->stop();
        return;
    }

    QgsSettings settings;
    QString baseKey = QStringLiteral( "/PostgreSQL/connections/" );
    settings.setValue( baseKey + "selected", ui->txtName->text() );
    bool hasAuthConfigID = !ui->mAuthSettings->configId().isEmpty();

    if ( !hasAuthConfigID && ui->mAuthSettings->storePasswordIsChecked( ) &&
         QMessageBox::question( this,
                                tr( "Saving Passwords" ),
                                tr( "WARNING: You have opted to save your password. It will be stored in unsecured plain text in your project files and in your home directory (Unix-like OS) or user profile (Windows). If you want to avoid this, press Cancel and either:\n\na) Don't save a password in the connection settings — it will be requested interactively when needed;\nb) Use the Configuration tab to add your credentials in an HTTP Basic Authentication method and store them in an encrypted database." ),
                                QMessageBox::Ok | QMessageBox::Cancel ) == QMessageBox::Cancel )
    {
        return;
    }
    // warn if entry was renamed to an existing connection
    if ( ( mOriginalConnName.isNull() || mOriginalConnName.compare( ui->txtName->text(), Qt::CaseInsensitive ) != 0 ) &&
         ( settings.contains( baseKey + ui->txtName->text() + "/service" ) ||
           settings.contains( baseKey + ui->txtName->text() + "/host" ) ) &&
         QMessageBox::question( this,
                                tr( "Save Connection" ),
                                tr( "Should the existing connection %1 be overwritten?" ).arg( ui->txtName->text() ),
                                QMessageBox::Ok | QMessageBox::Cancel ) == QMessageBox::Cancel )
    {
        return;
    }

    // on rename delete the original entry first
    if ( !mOriginalConnName.isNull() && mOriginalConnName != ui->txtName->text() )
    {
        settings.remove( baseKey + mOriginalConnName );
        settings.sync();
    }

    baseKey += ui->txtName->text();
    settings.setValue( baseKey + "/host", ui->txtHost->text() );
    settings.setValue( baseKey + "/port", ui->txtPort->text() );
    settings.setValue( baseKey + "/database", ui->txtDatabase->text() );
    settings.setValue( baseKey + "/username", ui->mAuthSettings->storeUsernameIsChecked( ) ? ui->mAuthSettings->username() : QString() );
    settings.setValue( baseKey + "/password", ui->mAuthSettings->storePasswordIsChecked( ) && !hasAuthConfigID ? ui->mAuthSettings->password() : QString() );
    settings.setValue( baseKey + "/authcfg", ui->mAuthSettings->configId() );
    settings.setValue( baseKey + "/publicOnly", ui->cb_publicSchemaOnly->isChecked() );
    settings.setValue( baseKey + "/geometryColumnsOnly", ui->cb_geometryColumnsOnly->isChecked() );
    settings.setValue( baseKey + "/dontResolveType", ui->cb_dontResolveType->isChecked() );
    settings.setValue( baseKey + "/allowGeometrylessTables", ui->cb_allowGeometrylessTables->isChecked() );
    settings.setValue( baseKey + "/sslmode", ui->cbxSSLmode->currentData().toInt() );
    settings.setValue( baseKey + "/saveUsername", ui->mAuthSettings->storeUsernameIsChecked( ) ? "true" : "false" );
    settings.setValue( baseKey + "/savePassword", ui->mAuthSettings->storePasswordIsChecked( ) && !hasAuthConfigID ? "true" : "false" );
    settings.setValue( baseKey + "/estimatedMetadata", ui->cb_useEstimatedMetadata->isChecked() );
    settings.setValue( baseKey + "/projectsInDatabase", ui->cb_projectsInDatabase->isChecked() );

    // remove old save setting
    settings.remove( baseKey + "/save" );

    //建立对数据库的连接，此时需要将右侧的导入导出信息清空
    mSchemaSet.clear();
    mSchema2Tables.clear();
    ui->cboSchema->clear();
    ui->cboTable->clear();
    ui->cboSchemaQuery->clear();
    ui->cboTableQuery->clear();

//    QgsDataSourceUri uri = QgsPostgresConn::connUri(mOriginalConnName);
    QgsDataSourceUri uri;
    uri.setConnection( ui->txtHost->text(), ui->txtPort->text(), ui->txtDatabase->text(),
                       ui->mAuthSettings->username(), ui->mAuthSettings->password(),
                       ( QgsDataSourceUri::SslMode ) ui->cbxSSLmode->currentData().toInt(),
                       ui->mAuthSettings->configId() );
    //当建立链接后，需要保持这个连接，直到程序结束
    mPostgresConn = QgsPostgresConn::connectDb(uri.connectionInfo(false),true);
    QList<QgsPostgresSchemaProperty> schemas;
    bool getSchemasResult = mPostgresConn->getSchemas(schemas);
    if(getSchemasResult){
        for(QgsPostgresSchemaProperty schemaProperty: schemas ){
            QString schema = schemaProperty.name;
            mSchemaSet.insert(schema);
            QVector<QgsPostgresLayerProperty> layers;
            bool getSupportedLayersResult = mPostgresConn->supportedLayers(layers, ui->cb_dontResolveType->isChecked(), ui->cb_publicSchemaOnly->isChecked(), ui->cb_allowGeometrylessTables->isChecked(), schema);
            if(getSupportedLayersResult){
                for(QgsPostgresLayerProperty layerProperty: layers){
                    if(mSchema2Tables.contains(schema)){
                        mSchema2Tables[schema].append(layerProperty.tableName);
                    }else{
                        QStringList tableNames;
                        tableNames.append(layerProperty.tableName);
                        mSchema2Tables.insert(schema, tableNames);
                    }
                }
            }
        }
    }

    //初始化数据导入和查询控件
    initImportDataToPostGIS();
    initQueryDataFromPostGIS();

    ui->statusBar->showMessage(tr("Connecting to %1 has estabilished...").arg(ui->txtDatabase->text()));
}

void QRSAGSDBManagerMainWindow::cb_geometryColumnsOnly_clicked()
{
    if ( ui->cb_geometryColumnsOnly->checkState() == Qt::Checked )
        ui->cb_publicSchemaOnly->setEnabled( false );
    else
        ui->cb_publicSchemaOnly->setEnabled( true );
}

void QRSAGSDBManagerMainWindow::updateOkButtonState()
{
    bool enabled = !ui->txtName->text().isEmpty() && (
                !ui->txtDatabase->text().isEmpty() );
    ui->mConnectionButton->setEnabled(enabled);
}

void QRSAGSDBManagerMainWindow::importSelectedLayerToPostgreSQL(bool)
{
    QString layerId = ui->cboInputLayer->currentData().toString();
    if(layerId.isEmpty()){
        return;
    }
    QgsDataSourceUri outUri = mPostgresConn->connUri(ui->txtName->text());
    QString currentSchema = outUri.schema();
    if(ui->cboSchema->isEnabled()){
        currentSchema = ui->cboSchema->currentText();
    }
//    QString currentTable = ui->cboTable->currentText();
    QString currentTable = ui->cboInputLayer->currentText();
    QgsMapLayer *mapLayer = QgsProject::instance()->mapLayer(layerId);
    QgsVectorLayer *currentMapLayer = nullptr;
    if(mapLayer->type() == QgsMapLayerType::VectorLayer){
        currentMapLayer = (QgsVectorLayer*)mapLayer;
    }else {
        QMessageBox::information(this, "Information", "Just support vector layer to import to database");
        return;
    }
//    QgsMapLayer *currentMapLayer = QgsProject::instance()->mapLayer(layerId);
    QgsDataSourceUri srcUri(currentMapLayer->source());
    QString currentPK = srcUri.keyColumn();
    if(ui->chkPrimaryKey->isChecked() && !ui->editPrimaryKey->text().isEmpty()){
        currentPK = ui->editPrimaryKey->text();
    }
    if(currentPK.isEmpty()){
        currentPK = mDefaultPK;
    }
    QString currentGeometry;
    if(currentMapLayer->isSpatial() && ui->chkGeomColumn->isEnabled()){
        currentGeometry = srcUri.geometryColumn();
        if(ui->chkGeomColumn->isChecked()){
            currentGeometry = ui->editGeomColumn->text();
        }
        if(currentGeometry.isEmpty()){
            currentGeometry = mDefaultGeom;
        }
    }
    QMap<QString, QVariant> options;
    if(ui->chkLowercaseFieldNames->isEnabled() && ui->chkLowercaseFieldNames->isChecked()){
        currentPK = currentPK.toLower();
        if(!currentGeometry.isEmpty()){
            currentGeometry = currentGeometry.toLower();
        }
        options.insert("lowercaseFieldNames", true);
    }
    outUri.setDataSource(currentSchema, currentTable, currentGeometry, "", currentPK);
    QString completeOutUri = outUri.uri(false);
    if(ui->chkDropTable->isChecked()){
        options.insert("overwrite", true);
    }

    if(ui->chkSinglePart->isEnabled() && ui->chkSinglePart->isChecked()){
        options.insert("forceSinglePartGeometryType", true);
    }

    QgsCoordinateReferenceSystem outCRS, inCRS;
    if(ui->chkTargetSrid->isEnabled() && ui->chkTargetSrid->isChecked()){
        outCRS = ui->widgetTargetSrid->crs();
    }
    if(ui->chkSourceSrid->isEnabled() && ui->chkSourceSrid->isChecked()){
        inCRS = ui->widgetSourceSrid->crs();
        currentMapLayer->setCrs(inCRS);
    }
    QString currentEncoding;
    if(ui->chkEncoding->isEnabled() && ui->chkEncoding->isChecked()){
        currentEncoding = ui->cboEncoding->currentText();
        currentMapLayer->setProviderEncoding(currentEncoding);
    }
    bool onlySelected = ui->chkSelectedFeatures->isChecked();
    QgsFeedback progressFeedback;
    connect( &progressFeedback, &QgsFeedback::progressChanged, this,
             [=](double progress)
    {
        ui->mImportDataProgressBar->setValue(progress);
        if(progress == 100){
            QMessageBox::information(this, "Import result", "Import vectorlayer to database has finished...");
        }
    });
    QgsVectorLayerExporter::ExportError exportError = QgsVectorLayerExporter::exportLayer(currentMapLayer, completeOutUri, "postgres", outCRS, onlySelected, nullptr, options, &progressFeedback);
}

void QRSAGSDBManagerMainWindow::expressionQuery(bool)
{
    QgsPostgresResult postgresResult;
    QString queryResult = "";
    QString querySQL = "SELECT * FROM public.counties_china where ";
    querySQL = querySQL + ui->mFieldComboBox->currentText() + "=" + ui->mQueryExpressionLineEdit->text();
    postgresResult = mPostgresConn->PQexec(querySQL, true);
    for(int idx = 0; idx < postgresResult.PQntuples(); idx++){
        QString id = postgresResult.PQgetvalue(idx, 0);
        QString adcode99 = postgresResult.PQgetvalue(idx, 2);
        QString last_name99 = postgresResult.PQgetvalue(idx, 3);
        QString ave_provin = postgresResult.PQgetvalue(idx, 4);
        QString first_name = postgresResult.PQgetvalue(idx, 4);
        queryResult +=
                "[id:" + id + "; " +
                "adcode99:" + adcode99 + "; " +
                "last_name99:" + last_name99 + "; " +
                "ave_provin:" + ave_provin + "; " +
                "first_name:" + first_name + "]";
    }

    ui->queryResultBrowser->setText(queryResult);
}

void QRSAGSDBManagerMainWindow::expressionClear(bool)
{
    ui->mQueryExpressionLineEdit->clear();
    ui->queryResultBrowser->clear();
}
